package com.wnxy.be_emp_manager.utils;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @PackgeName: com.yeheng.homework.utils
 * @ClassName: MyAuthenticatir
 * @Author: YH
 * Date: 2021/1/17 0:29
 * project name: homework
 * @Version:
 * @Description:
 */
public class MyAuthentication extends FormAuthenticationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
        resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("application/json;charset=utf8");
        PrintWriter writer = resp.getWriter();


        writer.write(JSON.toJSONString(null));
        writer.flush();
        writer.close();

        return false;
    }
}
